package com.zxu.test.util;

import android.app.Activity;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by yf
 * on 2016/1/26.
 */
public class ActivityUtils {

	public static ActivityUtils mInstance;
	private List<Activity> activityList;

	private ActivityUtils() {
	}

	public synchronized static ActivityUtils getInstance() {
		if (mInstance == null) {
			mInstance = new ActivityUtils();
		}
		return mInstance;
	}

	public void addActivity(Activity activity) {
		if (activityList == null) {
			activityList = new ArrayList<>();
		}
		activityList.add(activity);
	}

	public void finishAc() {
		if (activityList != null)
			for (Activity activity : activityList) {
				if (activity != null)
					activity.finish();
			}
	}

	public void clear() {
	    if(activityList == null) {
	        activityList = new ArrayList<>();
        }
	    activityList.clear();
    }

	public void removeAc(Activity activity){
		if (activity !=null && activityList != null && activityList.contains(activity))
			activityList.remove(activity);
	}

	public void exit() {
		try {
			for (Activity activity : activityList) {
				if (activity != null)
					activity.finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.exit(0);
		}
	}

    /**
     * The {@code fragment} is added to the container view with id {@code frameId}. The operation is
     * performed by the {@code fragmentManager}.
     *
     */
    public static void replaceFragmentInActivity(@NonNull FragmentManager fragmentManager,
                                                 @NonNull Fragment fragment, int frameId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(frameId, fragment);
        transaction.commit();
    }

    /**
     * The {@code fragment} is added to the container view with id {@code frameId}. The operation is
     * performed by the {@code fragmentManager}.
     *
     */
    public static void replaceFragmentInActivity(@NonNull FragmentManager fragmentManager,
                                                 @NonNull Fragment fragment, String tag) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(fragment, tag);
        transaction.commit();
    }
}
